"""
巡检巡查通用处理
"""
from config.common import INSPECT_PERSON_CONFIG, OSS_ACCESS_URL, PDF_IMAGE_PATH
import logging
from parser.pdf_parser import PDFParser
from handler.common_handler import parse_date_from_str, calc_hash, save_xjxc_result, \
    match_title, match_date, create_xjxc_parse_result_2, get_file_name
from handler.xjxc_parse_result import XjxcParseResult
import json
from utils.request_utils import request_get
from io import BytesIO


def parse_oss_pdf(pdf_path, doc_name):
    pdf_url = f"{OSS_ACCESS_URL}{pdf_path}"
    pdf_bytes: BytesIO = request_get(pdf_url)
    if pdf_bytes is not None:
        parser = PDFParser(pdf_bytes, "pdf")
        return do_parse(parser, get_file_name(pdf_path), doc_name)


def parse_local_pdf(pdf_path, doc_name):
    parser = PDFParser(pdf_path)
    return do_parse(parser, get_file_name(pdf_path), doc_name)


"""
table_separator_title：表格分隔符（根据每个表格的头部标题分割），用于解析工程名
doc_name：文档名称，用于解析任务名
"""


def do_parse(parser, file_name, doc_name):
    doc = parser.doc
    try:
        start_page = 0
        xjxc_results: list[XjxcParseResult] = []
        xjxc_result = None
        for page_num in range(len(doc)):
            logging.info(f"{file_name} Processing page {page_num}")
            page = doc[page_num]

            text = page.get_text()
            # 表格外部标题
            table_separator_title = match_title(text)
            if table_separator_title:
                # 巡检巡查日期
                inspect_date = parse_date_from_str(match_date(text), '%Y-%m-%d')
                if xjxc_result is None:
                    xjxc_result = create_xjxc_parse_result_2(table_separator_title, doc_name, inspect_date)

                end_page = page_num
                # 保存上一个表格的信息
                if end_page > 0:
                    save_xjxc_result(xjxc_results, xjxc_result, doc, doc_name, inspect_date, start_page, end_page)
                start_page = page_num
                xjxc_result = create_xjxc_parse_result_2(table_separator_title, doc_name, inspect_date)

            # 最后一页
            if page_num == len(doc) - 1 and xjxc_result is not None:
                end_page = len(doc)
                save_xjxc_result(xjxc_results, xjxc_result, doc, doc_name, inspect_date, start_page,
                                 end_page)

            # 提取图片
            images = parser.extract_images_page2(page_num, page)
            # 计算图像的哈希值
            if images is not None and len(images) > 0:
                image_bytes = images[len(images) - 1].image_data['image']
                inspect_person_image_hash = calc_hash(image_bytes)
                # 保存图片(测试获取哈希值使用)
                with open(f'{PDF_IMAGE_PATH}/{inspect_person_image_hash}.png', 'wb') as image_file:
                    image_file.write(image_bytes)
                if xjxc_result is not None:
                    xjxc_result.inspect_person = INSPECT_PERSON_CONFIG.get(inspect_person_image_hash)
        return xjxc_results
    finally:
        doc.close()


if __name__ == '__main__':
    xjxc_results = parse_local_pdf(
        r'E:/work/hispatial/shaoxing/知识库/知识库相关资料/2023年台账资料/高压配电系统检查记录表/一月份高压配电系统检查记录表.pdf',
        '一月份高压配电系统检查记录表')

    # xjxc_results = parse_oss_pdf('knowledge-base/2024-12-04/一月份变压器检查记录表_50a3c61dedf226fd.pdf',
    #                              '一月份变压器检查记录表')
    print(json.dumps([xjxc_result.to_dict() for xjxc_result in xjxc_results], ensure_ascii=False))
